# -*- encoding: utf-8 -*-
'''
Filename         :16_threeSumClosest.py
Description      :
Time             :2022/08/09 10:11:18
Author           :daiyizheng
Email            :387942239@qq.com
Version          :1.0
'''

from typing import List


class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        n = len(nums)
        re_min = 0
        nums.sort()

        for i in range(n):
            low = i+1
            high = n-1
            while low < high:
                three_sum = nums[i] + nums[low] + nums[high]
                x = target - three_sum # 当前三数的差值
                if re_min ==0:
                    re_min = abs(x)
                    sum_min = three_sum
                if abs(x) < re_min:
                    re_min = abs(x)
                    sum_min = three_sum
                
                if three_sum == target:
                    return target
                elif three_sum < target:
                    low += 1
                else:
                    high -= 1
        return sum_min
                